// package: rewords-server-2024
// filename: admin
// author: diogoxiang@gmail.com
// time: 2024/11/18 10:08

package admin

import (
	"context"
	"rewords-server-2024/api/admin"
	"rewords-server-2024/internal/consts"
	"rewords-server-2024/internal/library/cache"
	"rewords-server-2024/internal/service"

	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
	"go.mongodb.org/mongo-driver/bson"

	"github.com/gogf/gf/v2/errors/gerror"
)

var AmisStatic = new(cAmisStatic)

type cAmisStatic struct{}

func (c *cAmisStatic) QueryInfo(ctx context.Context, req *admin.AmisPageReq) (res *admin.AmisPageRes, err error) {
	r := g.RequestFromCtx(ctx)

	pathName := r.GetRouter("path").String()

	selectMap := bson.M{
		"path_name": "/" + pathName,
	}

	schemaCache, err := cache.Instance("pages").Get(ctx, "/"+pathName)
	if err == nil && schemaCache != nil {
		// 有缓存直接返回
		r.Response.WriteJson(schemaCache.Map())
		return
	}

	result, err := service.Mgx().FindOne(ctx, consts.CAmisSchema, selectMap, nil)

	if err != nil {
		return nil, gerror.Wrap(err, "获取数据失败")
	}
	schemaJSON := gjson.New(result["schema"])

	// 缓存
	cache.Instance("pages").Set(ctx, "/"+pathName, schemaJSON.Map(), 0)

	// 将结果转换为JSON并直接返回
	r.Response.WriteJson(schemaJSON.Map())

	return
}
